package jp.ac.aiit.yc.softarch.hbcp.service.common;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;


import jp.ac.aiit.yc.softarch.hbcp.model.common.LoginResult;
import jp.ac.aiit.yc.softarch.hbcp.model.common.User;

public class LoginService {



	protected boolean isExists(User user) {
		for (User u : UserManagementService.users) {
			if (u.name.equals(user.name) && u.password.equals(user.password) && u.isLogined == false) {
				System.out.println(user.name + " is exists");
				u.isLogined = true;//ログインフラグを立てる
				return true;
			}
		}
		System.out.println(user.name + " is not exists");
		return false;
	}

	public LoginResult canLogin(User user) {//ログイン判定を行うメソッド
		System.out.println("doing LoginService.canLogin() : " + CalendarUtil.nowDate());
		LoginResult lr = new LoginResult();//ログイン判定結果オブジェクトを作成する
		for (User u : UserManagementService.users) {
			if (u.name.equals(user.name) && u.password.equals(user.password) && u.isLogined == false) {
				lr.result = true;
				u.isLogined = true;//ログインフラグを立てる
				System.out.println(user.name + " can login");
				return lr;
			}
			if (u.name.equals(user.name) && u.password.equals(user.password) && u.isLogined == true) {//重複ログインの検出
				lr.isRedundant = true;//重複ログインフラグを立てる
				System.out.println(user.name + " try to redundant login");
			}
		}
		System.out.println(user.name + " can not login");
		return lr;
	}

	public boolean adminLogin(User user) {
		System.out.println("doing LoginService.adminLogin() : " + CalendarUtil.nowDate());
		for (User u : UserManagementService.adminUsers) {
			if (u.name.equals(user.name) && u.password.equals(user.password)) {
				System.out.println(user.name + " is exists");
				return true;
			}
		}
		System.out.println(user.name + " is not exists");
		return false;
	}

	public void readUsers()throws Exception{//小島DBテスト用
		System.out.println("doing readUsers()");
		Class.forName("org.hsqldb.jdbcDriver");
		Connection connection = DriverManager.getConnection("jdbc:hsqldb:file:/HBCP_DB/hbcp_dbFile;shutdown=true", "sa", null);
		Statement stmt = connection.createStatement();
		stmt.executeQuery("CREATE MEMORY TABLE CARD(NAME VARCHAR,PASSWORD VARCHAR)");
		stmt.executeQuery("INSERT INTO USER VALUES('user1','user1')");
		stmt.executeQuery("INSERT INTO USER VALUES('user2','user2')");
		stmt.executeQuery("INSERT INTO USER VALUES('user3','user3')");
		stmt.executeQuery("INSERT INTO USER VALUES('oka','oasamu')");
		stmt.executeQuery("INSERT INTO USER VALUES('okino','tomoki')");
		stmt.executeQuery("INSERT INTO USER VALUES('sugita','toshinao')");
		//rs.close();
		stmt.close();
		connection.close();
		return;
	}
}
